import React, { Component } from 'react';
import { Modal, Form, Input,Radio,Select,DatePicker,Popconfirm ,Row,Col,Button,Icon,Upload, message} from 'antd';
import styles from '../item.less';
import moment from 'moment'
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';
const config = require('../../config');

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

class _Modal extends Component {

  constructor(props) {
    super(props);
    let _components = {}
    let _figures=[];
    Array.from(props.record.components||[]).map(d=>{
        d.id = d.id || 'key-'+parseInt(Math.random()*10000)
        _components[d.id] = d
    })
    Array.from(props.record.figures||[]).map(d=>{
        _figures[d.uid]=-(d.id);
        _figures[d.name]=d.id;
        _figures[d.status]='done';
        _figures[d.url]=d.pic;
        _figures[d.thumbUrl]=d.thumbUrl;
    });
    this.state = {
      visible: false,
      components:_components,
      imgfigures:_figures,
      imageUrl:props.record.pic,
      figures:props.record.figures || [],
    };
  }

  showModelHandler = (e) => {
    if (e) e.stopPropagation();
    this.setState({
      visible: true,
    });
  };

  hideModelHandler = () => {
    this.setState({
      visible: false,
    });
  };
  handleAddCp = (e) =>{
      let coms = Object.assign({},this.state.components)
      let n = {component_num:'',quantity:'',id:'new'+Date.now()}
      coms[n.id] = n
      this.setState({components:coms})
  };
  handleDelCp = (componnentId) =>{
      let coms = Object.assign({},this.state.components)
      delete coms[componnentId]
      this.setState({components:coms})
  };
  updateComponnect = (id,key,value)=>{
      console.log({id,key,value})
      let coms = Object.assign({},this.state.components)
      coms[id][key] = value
      this.setState({components:coms})
  };
  updatePic = (info)=>{
      if (info.file.status === 'done') {
          let newMd5 = info.file.response.md5list[0]
          console.log('new md5',newMd5)
          getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl:newMd5}));
      }
  }

  updateFigures = (info)=>{
      if (info.file.status === 'done') {
          console.log('info',info)
          let newMd5 = info.file.response.md5list[0]
          console.log('updateFigures new md5',newMd5)
          let _figures = Array.from(this.state.figures);
           _figures.push({pic:newMd5})
           getBase64(info.file.originFileObj, imageUrl => this.setState({figures:_figures}));
          // _figures.push({pic:newMd5})
          // this.setState({figures:_figures})
          // getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl:newMd5}));
      }
  }
  handleSubmit = (e) => {
      let comps = Object.values(this.state.components)
      comps.map(d=>{
          delete d.id
      })
      let pic = this.state.imageUrl;
      let figures=this.state.figures;
      let return2Father = this.props.return2Father
      let item = Object.assign({},this.props.record)
      this.props.form.validateFields((err, values) => {
          console.log('err',err)
        if (!err) {
            item = Object.assign(item,values)
            item.components = comps;
            item.pic = pic;
            item.figures=figures;
            return2Father(item)
            this.hideModelHandler()
        }
      });

  };
  render() {
    const { children } = this.props;
    console.log(children,'children');
    const { getFieldDecorator } = this.props.form;
    const fileList = this.state.imgfigures;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const props2 = {
        action: config.url+'/file/upload',
        listType: 'picture',
        defaultFileList: [...fileList],
        className: 'upload-list-inline',
    };
    return (
      <span>
        <span onClick={this.showModelHandler}>
          { children }
        </span>
        <Modal
          title={'cnum' in this.props.record ? '修改：'+this.props.record.cnum:'新建一条商品信息'}
          visible={this.state.visible}
          onCancel={this.hideModelHandler}
          onOk={this.handleSubmit}
        >
        <Form layout="horizontal" >
              <FormItem className={styles.FormItem} {...formItemLayout} label="商品名字" hasFeedback>
                {getFieldDecorator('name', {initialValue: this.props.record.name,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
              </FormItem>
              <FormItem className={styles.FormItem} {...formItemLayout} label="型号" hasFeedback>
                {getFieldDecorator('model', {initialValue: this.props.record.model,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
              </FormItem>
              <FormItem className={styles.FormItem} {...formItemLayout} label="商品尺寸" hasFeedback>
                {getFieldDecorator('size', {initialValue: this.props.record.size,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
              </FormItem>
              <FormItem className={styles.FormItem} {...formItemLayout} label="供应商编号" hasFeedback>
                {getFieldDecorator('brand_num', {initialValue: this.props.record.brand_num,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
              </FormItem>
              <FormItem className={styles.FormItem} {...formItemLayout} label="部件*数量" >
                {Object.keys(this.state.components).map(id=>
                    <Row key={id}>
                    <Col span="4">
                    <FormItem>
                        <Input size="small" defaultValue={this.state.components[id].name} onChange={e=>this.updateComponnect(id,'name',e.target.value)}/>
                    </FormItem>
                  </Col>
                  <Col span="1">
                    <p className="ant-form-split">*</p>
                  </Col>
                  <Col span="4">
                      <FormItem>
                          <Input size="small" defaultValue={this.state.components[id].quantity} onChange={e=>this.updateComponnect(id,'quantity',e.target.value)}/>
                      </FormItem>
                  </Col>
                  <Col span="4">
                      <Button  size="small" onClick={e=>this.handleDelCp(id)}>删除</Button>
                  </Col>
                  </Row>
                )}
                <Button  size="small" onClick={this.handleAddCp} >添加</Button>
              </FormItem>
              <FormItem className={styles.FormItem} {...formItemLayout} label="图片(点击更换)" >
                <Upload multiple={true} action={config.url+'/file/upload'} onChange={this.updatePic}>
                    <img style={{width:"50px",heigth:"50px"}} src={config.url+'/file/'+this.state.imageUrl}/>
                </Upload>
              </FormItem>
              <FormItem className={styles.FormItem} {...formItemLayout} label="附图(点击更换)" >
                <Upload multiple={true} action={config.url+'/file/upload' }onChange={this.updateFigures}>
                    <span>附图:</span>
                    {this.state.figures.map(d=><img key={d.pic} style={{width:"50px",heigth:"50px"}} src={config.url+'/file/'+d.pic}/>)}
                </Upload>
              </FormItem>
        </Form>
        </Modal>
      </span>
    );
  }
}

export default Form.create()(_Modal);
